<template>
  <div class="userBox">
    <!-- 搜索 -->
    <Search
      @search="searchUser"
      title="账号/姓名:"
      placeholder="请输入账号、姓名"
    ></Search>
    <!-- 添加 -->
    <tableHeaderVue>
      <template #default>
        <el-button class="button" type="primary" @click="unitPage"
          >初始当前列表</el-button
        >
        <el-button class="button" type="primary" @click="addFlag = true"
          >添加</el-button
        >
      </template>
    </tableHeaderVue>
    <!-- 表单 -->
    <div class="table">
      <el-table :data="tableList" border width="100%">
        <el-table-column prop="id" label="编号" />
        <el-table-column prop="username" label="账号" />
        <el-table-column prop="nickName" label="姓名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column label="添加时间">
          <template #default="scope">
            {{ handleDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="最后登录">
          <template #default="scope">
            {{ handleDate(scope.row.loginTime) }}
          </template>
        </el-table-column>
        <el-table-column label="是否启用">
          <template #default="scope">
            <el-switch
              @click="changeStatus(scope)"
              :model-value="scope.row.status"
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
              :active-value="1"
              :inactive-value="0"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="157px">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              text
              @click="changeRole(scope.row.id)"
              >分配角色</el-button
            >
            <el-button
              type="primary"
              size="small"
              text
              @click="editUser(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              text
              @click="delUser(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination
        v-model:currentPage="pagination.currentPage"
        v-model:page-size="pagination.currentSize"
        :page-sizes="[10, 20, 50, 100]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <template #total>
          <div>11</div>
        </template>
      </el-pagination>
    </div>
    <!-- 分配角色 -->
    <div class="dispatch">
      <el-dialog v-model="dispatchFlag" title="分配角色">
        <div style="display: inline-block">
          <el-select
            v-model="dispatchList"
            multiple
            placeholder="请选择"
            style="width: 280px"
          >
            <el-option
              v-for="item in dispatchListValue"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
        <template #footer>
          <el-button @click="dispatchFlag = false" size="large">取消</el-button>
          <el-button type="primary" @click="openDispatch" size="large"
            >确定</el-button
          >
        </template>
      </el-dialog>
    </div>
    <!-- 编辑用户信息 -->
    <adminEditDialog
      title="添加用户"
      :editFlag="editFlag"
      :id="handleUserId"
      @unitPage="getTableList"
      :userInfoForm="userInfoForm"
      @openEditDialog="editFlag = true"
      @closeEditDialog="editFlag = false"
    ></adminEditDialog>
    <!-- 添加新用户 -->
    <adminAddDialog
      title="添加用户"
      :addFlag="addFlag"
      @openAddDialog="addFlag = true"
      @closeAddDialog="addFlag = false"
    ></adminAddDialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref, Ref, nextTick } from "vue";
import * as http from "@/request";
import Search from "@/components/search.vue";
import tableHeaderVue from "@/components/tableHeader.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { handleDate } from "@/utils";
import adminAddDialog from "./component/adminAddDialog.vue";
import adminEditDialog from "./component/adminEditDialog.vue";
import { useTable } from "@/hooks/useTable";
let newSearch = ref("");
// 添加用户
let addFlag = ref(false);
// 编辑用户信息弹窗状态
let editFlag = ref(false);
const {
  tableList,
  getTableList,
  pagination,
  handleSizeChange,
  handleCurrentChange,
  searchListContent,
} = useTable(http.adminList, { keyword: newSearch });
// 数据相关
type IUserList = {
  dispatchList: number[];
  userInfoForm: IUserListDataItem;
  dispatchListValue: IRoleListItem[];
};
const userList = reactive<IUserList>({
  dispatchList: [],
  userInfoForm: {
    createTime: "",
    email: "",
    icon: "",
    id: 0,
    loginTime: "",
    nickName: "",
    note: "",
    password: "",
    status: -1,
    username: "",
  },
  // 用户权限相关数据
  dispatchListValue: [],
});

// 添加所用表单
// let addUserFrom = ref({} as IAddUserInfo);
// 解构数据
const { dispatchList, userInfoForm, dispatchListValue } = toRefs(userList);
// 要处理用户的id
let handleUserId = ref(0);

// 初始化列表
const unitPage = async () => {
  newSearch.value = "";
  pagination.currentPage = 1;
  pagination.currentSize = 10;
  await nextTick();
  getTableList();
};

// 搜索功能
const searchUser = async (keyword: Ref<string>) => {
  newSearch.value = keyword.value;
  await nextTick();
  // 延迟调用搜索函数
  searchListContent();
};
// 分配角色弹框
let dispatchFlag = ref(false);
// 打开修改用户角色窗口
const changeRole = async (id: number) => {
  handleUserId.value = id;
  dispatchFlag.value = true;
  let res = await http.adminRole(id);
  if (res.code === 200) {
    // 获取权限对应id
    // 先置空, 防止重复取消累加
    userList.dispatchList = [];
    res.data.forEach((item) => {
      
      if (item) {
        userList.dispatchList.push(item.id);
      }
    });
  }
  let res2 = await http.roleListAll();
  if (res2.code === 200) {
    userList.dispatchListValue = res2.data;
  }
};
// 再次打开确认修改权限页面
const openDispatch = () => {
  ElMessageBox.confirm("此操作将修改当前哟用户角色, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
  })
    .then(async () => {
      // 需要表单类型数据
      const from = new FormData();
      from.append("adminId", String(handleUserId.value));
      from.append("roleIds", dispatchList.value.join(","));
      const res = await http.adminRoleUpdate(from);
      if (res.code === 200) {
        dispatchFlag.value = false;
        // 重新获取当前用户信息
        // oneUnitPage();
        ElMessage({
          message: res.message,
          type: "success",
        });
      }
    })
    .catch(() => {});
};

const editUser = async (userInfo: IUserListDataItem) => {
  handleUserId.value = userInfo.id;
  userList.userInfoForm = { ...userInfo };
  await nextTick();
  editFlag.value = true;
};

// 改变用户状态
const changeStatus = async (scope: any) => {
  // console.log(scope.row);
  let currentUser = tableList.value.find((item) => item.id === scope.row.id);
  // 规避客户端服务器不兼容
  let status: 0 | 1 = currentUser!.status ? 0 : 1;
  let res = await http.adminUpdateStatus(currentUser!.id, status);
  if (res.code === 200) {
    // 成功之后再修改本地数据
    currentUser!.status = status;
    ElMessage({
      message: res.message,
      type: "success",
    });
  }
};

// 删除用户
const delUser = (id: number) => {
  ElMessageBox.confirm("此操作将删除用户, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
  })
    .then(async () => {
      let res = await http.adminDelete(id);
      if (res.code === 200) {
        // 重新获取当前用户信息
        getTableList();
        ElMessage({
          message: res.message,
          type: "success",
        });
      } else {
        ElMessage({
          message: res.message,
          type: "error",
        });
      }
    })
    .catch(() => {});
};
</script>
<style lang="scss" scoped>
.userBox {
  display: flex;
  flex-direction: column;
  padding: 10px 20px;
  box-sizing: border-box;
  width: 100%;
}
:deep(.cell) {
  text-align: center;
  font-size: 12px;
}
.table {
  :deep(.el-button) {
    padding: 10px 0;
  }
}
.dispatch {
  :deep(.el-dialog) {
    width: 400px;
  }
}
.page {
  display: flex;
  justify-content: flex-end;
  padding-top: 20px;
}
</style>
